<template>
	<a-modal
		:open="props.open"
		:width="
			props.modelInfo && props.modelInfo.width ? props.modelInfo.width : '900px'
		"
		:title="
			props.modelInfo && props.modelInfo.title ?
				props.modelInfo.title
			:	'Basic Modal'
		"
		:confirmLoading="modelConfig.confirmLoading"
		:destroyOnClose="modelConfig.destroyOnClose"
		@cancel="handleCancel"
	>
		<template #footer>
			<a-button key="back" @click="handleCancel">取消</a-button>
			<a-button key="submit" type="primary" :loading="loading" @click="handleOk"
				>保存</a-button
			>
		</template>
		<a-form
			ref="formRef"
			name="OfflineServiceProviderForm"
			class="ant-advanced-search-form"
			:model="formState"
			:rules="rulesRef"
			:label-align="'right'"
		>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item
						:name="labelMap['name'].name"
						:label="labelMap['name'].label"
					>
						<a-input
							v-model:value="formState.name"
							:placeholder="'请填写' + labelMap['name'].label"
						></a-input>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item
						:name="labelMap['phoneNumber'].name"
						:label="labelMap['phoneNumber'].label"
					>
						<a-input
							v-model:value="formState.phoneNumber"
							:placeholder="'请填写' + labelMap['phoneNumber'].label"
						></a-input>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item
						:name="labelMap['provinceInfo'].name"
						:label="labelMap['provinceInfo'].label"
					>
						<a-cascader
							v-model:value="formState.provinceInfo"
							:options="locationTree"
							:placeholder="'请填写' + labelMap['provinceInfo'].label"
							:load-data="loadData"
							:fieldNames="{ label: 'name', value: 'id', children: 'children' }"
							change-on-select
							@change="handleChange"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item
						:name="labelMap['userId'].name"
						:label="labelMap['userId'].label"
					>
						<a-select
							v-model:value="formState.userId"
							:placeholder="'请填写' + labelMap['userId'].label"
							:options="userList"
							:filter-option="filterOption"
							:field-names="{ value: 'id', label: 'code' }"
							show-search
							allow-clear
							:disabled="props.modelInfo?.id != null"
						>
						</a-select>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item
						:name="labelMap['singleFlag'].name"
						:label="labelMap['singleFlag'].label"
						v-if="formState.type === 'partner'"
					>
						<a-select
							v-model:value="formState.singleFlag"
							:placeholder="'请填写' + labelMap['singleFlag'].label"
							:options="flagList"
							:filter-option="filterOption"
							:field-names="{ value: 'value', label: 'label' }"
							show-search
							allow-clear
						>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item
						:name="labelMap['partnerType'].name"
						:label="labelMap['partnerType'].label"
						v-if="formState.type === 'partner'"
					>
						<a-select
							v-model:value="formState.partnerType"
							:placeholder="'请填写' + labelMap['partnerType'].label"
							:options="partnerConfigList"
							:filter-option="filterOption"
							:field-names="{ value: 'categoryCode', label: 'categoryName' }"
							show-search
							@change="handlePartnerTypeChange"
						>
						</a-select>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item
						:name="labelMap['partnerTypeAmount'].name"
						:label="labelMap['partnerTypeAmount'].label"
						v-if="formState.type === 'partner'"
					>
						{{ partnerTypeAmount }}
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="24">
					<a-form-item
						:name="labelMap['demandDescription'].name"
						:label="labelMap['demandDescription'].label"
					>
						<a-textarea
							v-model:value="formState.demandDescription"
							:placeholder="'请填写' + labelMap['demandDescription'].label"
						></a-textarea>
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
	</a-modal>
</template>
<script lang="ts" setup>
import {
	OfflineServiceProviderDetail,
	labelMap,
	rulesRef,
	flagList,
} from './userPartnerDetailTs';
import {
	getOfflineServiceProviderDetail,
	addOrEditOfflineServiceProvider,
} from '@/api/userInfo/offlineServiceProvider/offlineServiceProviderTs';
import { getPartnerCategoryConfigList } from '@/api/userInfo/partnerCategoryConfig/partnerCategoryConfigTs';
import { getUserInfoList } from '@/api/userInfo/userInfo/userInfoTs';
import { getLocationTree } from '@/api/eventInfo/eventInfo/eventInfoTs';
import { message, FormInstance } from 'ant-design-vue';
import { ModelInfo } from '../userPartnerListTs';
import { filterOption } from '@/utils/common';
import { reduceMoneyInfo } from '@/api/userBalanceInfo/index';

let loading = ref<boolean>(false);

const formRef = ref<FormInstance>();

const locationTree = ref<any[]>([]);

const firstChange = ref<boolean>(true);

const partnerConfigList = ref<any[]>([]);

const partnerTypeAmount = ref<number | null>(null);

const modelConfig = {
	confirmLoading: true,
	destroyOnClose: true,
};

interface Props {
	open?: boolean;
	modelInfo?: ModelInfo;
}
const props = defineProps<Props>();

let formState = ref<OfflineServiceProviderDetail>({});

const userList = ref<any>([]);

const handleOk = async (): Promise<void> => {
	if (formRef.value) {
		await formRef.value.validateFields();
		loading.value = true;
		saveOfflineServiceProviderManager();
	}
};

const handleCancel = (): void => {
	emit('handleCancel', false);
};

const getLocationTreeInfo = async (parentId: number): Promise<any> => {
	const { data, code, message } = await getLocationTree({ parentId }).catch(
		(error: any) => {
			console.log(`getLocationTree error：`, error);
			message.error('查询失败！');
		},
	);
	if (code == '200') {
		return data;
	} else {
		message.error(message || '查询失败！');
		return null;
	}
};

const loadData = async (selectedOptions: any[]) => {
	const targetOption = selectedOptions[selectedOptions.length - 1];
	targetOption.loading = true;
	targetOption.children = await getLocationTreeInfo(targetOption.id);
	if (targetOption.children.length == 0) {
		return;
	}
	targetOption.children.forEach((item: any) => {
		if (targetOption.level == 1) {
			item.isLeaf = false;
			item.level = 2;
		} else {
			item.isLeaf = true;
			item.level = 3;
		}
	});
};

const handleChange = (value: any) => {
	if (formState.value?.provinceInfo?.length == 3) {
		firstChange.value = false;
		return;
	}
	firstChange.value = false;
	formState.value.provinceInfo = [];
};

//保存线下服务商表信息
const saveOfflineServiceProviderManager = async (): Promise<void> => {
	let method = '';
	let params = {
		id: formState.value.id,
		name: formState.value.name,
		phoneNumber: formState.value.phoneNumber,
		demandDescription: formState.value.demandDescription,
		userId: formState.value.userId,
		type: formState.value.type,
		provinceId:
			firstChange.value ?
				formState.value?.provinceId
			:	formState.value.provinceInfo[0],
		cityId:
			firstChange.value ?
				formState.value?.cityId
			:	formState.value.provinceInfo[1],
		districtId:
			firstChange.value ?
				formState.value?.districtId
			:	formState.value.provinceInfo[2],
		partnerType: formState.value.partnerType,
		singleFlag: formState.value.singleFlag,
		status: formState.value.status,
	};
	console.log(`params sssssssssssssssssssss`, params, formState.value);
	if (formState.value.id) {
		method = 'put';
	} else {
		method = 'post';
	}

	if (formState.value.id || formState.value.type === 'emotion') {
		addOrEditOfflineServiceProvider(method, params)
			.then((res) => {
				if (res.code == '200') {
					message.success((res && res.message) || '保存成功！');
					formState.value = {};
					emit('handleOk', false);
				} else {
					message.error((res && res.message) || '保存失败！');
				}
			})
			.catch((error: any) => {
				message.error(error?.message || '查询失败！');
			})
			.finally(() => {
				loading.value = false;
			});
	} else {
		let currentParams = {
			relatedBusinessInfo: JSON.stringify(params),
			type: 'partner',
			amount: partnerTypeAmount.value,
			userId: formState.value.userId,
			source: 'end',
		};
		const { code, message: messageInfo } = await reduceMoneyInfo(currentParams)
			.catch((error: any) => {
				message.error(error?.message || '查询失败！');
			})
			.finally(() => {
				loading.value = false;
			});
		if (code == '200') {
			message.success('创建订单成功，请到订单中进行审核！');
			formState.value = {};
			emit('handleOk', false);
		} else {
			message.error(messageInfo || '保存失败！');
		}
	}
};

// 查询用户信息
const getUserInfoListInfo = async () => {
	let params = {};
	let res = await getUserInfoList(params);
	const { code, data, message: messageInfo } = res;
	if (code === '200') {
		userList.value = data;
	} else {
		userList.value = [];
		message.warn(messageInfo || '失败，请联系管理员！');
	}
};

// 查询合伙人类型列表
const getPartnerCategoryConfigListInfo = async () => {
	let res = await getPartnerCategoryConfigList({});
	const { code, data, message: messageInfo } = res;
	if (code === '200') {
		partnerConfigList.value = data;
	} else {
		message.warn(messageInfo?.description || '失败，请联系管理员！');
	}
};

const handlePartnerTypeChange = (_value: any, option: any) => {
	partnerTypeAmount.value = option.price;
};

const init = async (): Promise<void> => {
	locationTree.value = await getLocationTreeInfo(0);
	await getUserInfoListInfo();
	await getPartnerCategoryConfigListInfo();
	locationTree.value.forEach((item) => {
		item.isLeaf = false;
		item.level = 1;
	});
	if (props.modelInfo) {
		if (props.modelInfo.id) {
			getOfflineServiceProviderDetail(props.modelInfo.id)
				.then((res) => {
					if (res.code == '200') {
						formState.value = res.data;
						formState.value.provinceInfo = [
							res.data?.provinceName,
							res.data?.cityName,
							res.data?.districtName,
						];
						modelConfig.confirmLoading = false;
					} else {
						message.error((res && res.message) || '查询失败！');
					}
				})
				.catch((error: any) => {
					message.error(error?.message || '查询失败！');
				});
		} else {
			modelConfig.confirmLoading = false;
			formState.value = {
				type: 'partner',
			};
		}
	}
};

const emit = defineEmits(['handleOk', 'handleCancel']);

watch(
	() => props.open,
	(newVal) => {
		if (newVal) {
			init();
		}
	},
	{
		immediate: true,
		deep: true,
	},
);

defineExpose({ handleOk, handleCancel });
</script>
<style lang="scss" scoped></style>
